package com.woniu.zsd.platform.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.zsd.common.util.DistanceUtil;
import com.woniu.zsd.common.util.Result;
import com.woniu.zsd.common.web.PageInfo;
import com.woniu.zsd.platform.dao.AccountMapper;
import com.woniu.zsd.platform.dao.AccountRoleMapper;
import com.woniu.zsd.platform.dto.RecycleBinLocationDto;
import com.woniu.zsd.platform.model.Account;
import com.woniu.zsd.platform.model.AccountRole;
import com.woniu.zsd.platform.model.RecycleBin;
import com.woniu.zsd.platform.dao.RecycleBinMapper;
import com.woniu.zsd.platform.param.AddRecycleBinParam;
import com.woniu.zsd.platform.param.SelectStationParam;
import com.woniu.zsd.platform.param.UpdateRecycleBinParam;
import com.woniu.zsd.platform.param.UpdateSiteScoreBySiteIdParam;
import com.woniu.zsd.platform.service.RecycleBinService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.zsd.recycle.feign.RecycleFeignClient;
import org.apache.ibatis.javassist.expr.NewArray;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhangtao
 * @since 2025年02月18日
 */
@Service
public class RecycleBinServiceImpl extends ServiceImpl<RecycleBinMapper, RecycleBin> implements RecycleBinService {
    @Resource
    private RecycleFeignClient recycleFeignClient;
    @Resource
    private AccountRoleMapper accountRoleMapper;
    @Resource
    private AccountMapper accountMapper;

    @Resource
    private RecycleBinMapper recycleBinMapper;

    @Override
    public String selectStationNameByStationId(Integer stationId) throws Exception {
        String stationName = recycleBinMapper.selectStationNameByStationId(stationId);
        return stationName;
    }

    @Override
    public void updateSiteScoreBySiteId(UpdateSiteScoreBySiteIdParam param) throws Exception {
        RecycleBin recycleBin = recycleBinMapper.selectById(param.getStationId());
        if(recycleBin== null){
            throw new Exception("站点不存在");
        }
        recycleBin.setRating(param.getRating());
        recycleBinMapper.updateById(recycleBin);
    }

    @Override
    public List<Integer> selectRecycleBinByLocation(BigDecimal longitude, BigDecimal latitude) {
        List<RecycleBinLocationDto> dtos = recycleBinMapper.selectRecycleBinByLocation();
        // 创建一个Map来保存站点和距离
        Map<RecycleBinLocationDto, Double> stationDistanceMap = new HashMap<>();

        // 计算每个站点到用户的距离
        for (RecycleBinLocationDto dto : dtos) {
            double distance = DistanceUtil.calculateDistance(longitude, latitude, dto.getLongitude(), dto.getLatitude());
            if (distance <= 20.0) { // 只保留距离小于等于20公里的站点
                stationDistanceMap.put(dto, distance);
            }
            stationDistanceMap.put(dto, distance);
        }

        // 如果没有站点小于等于20公里，返回空列表
        if (stationDistanceMap.isEmpty()) {
            return Collections.emptyList();
        }


        // 按照距离排序，并取前5个站点
        return stationDistanceMap.entrySet().stream()
                .sorted(Map.Entry.comparingByValue()) // 按距离升序排序
                .limit(5) // 取前5个站点
                .map(entry -> entry.getKey().getStationId()) // 提取站点ID
                .collect(Collectors.toList());
    }

    @Override
    public void addRecycleBin(AddRecycleBinParam param) throws Exception {
        QueryWrapper<RecycleBin> wrapper = new QueryWrapper<>();
        wrapper.eq("station_name", param.getStationName());
        RecycleBin recycleBin = recycleBinMapper.selectOne(wrapper);
        if(recycleBin!= null){
            throw new Exception("站点名称已存在");
        }
        //绑定用户
        Account account = accountMapper.selectOne(new QueryWrapper<Account>().eq("account_name", param.getChiefName()));
        if(account == null){
            throw new Exception("用户不存在");
        }
//        Account account1 = new Account();
//        account1.setPassword("123456");
//        account1.setPhone(param.getPhone());
//        account1.setAccountName(param.getChiefName());
        //更改用户状态
        account.setStatus(1);
        accountMapper.updateById(account);
        //绑定角色
        AccountRole accountRole = new AccountRole();
        accountRole.setAccountId(account.getAccountId());
        accountRole.setRoleId(3);
        accountRoleMapper.insert(accountRole);
        //添加站点
        RecycleBin bin = BeanUtil.toBean(param, RecycleBin.class);
        bin.setRegistrationDate(LocalDate.now());
        bin.setStatus(1);
        System.out.println(bin);
        recycleBinMapper.insert(bin);
        //把平台规定好的类型和价格复制到站点表
        recycleFeignClient.updatePriceByStationId(bin.getStationId());
    }

    @Override
    public void deleteRecycleBin(Integer stationId) throws Exception {
        RecycleBin recycleBin = recycleBinMapper.selectById(stationId);
        if(recycleBin == null){
            throw new Exception("站点不存在");
        }
        recycleBinMapper.deleteById(stationId);
    }

    @Override
    public void updateRecycleBin(UpdateRecycleBinParam param) throws Exception {
        RecycleBin recycleBin = recycleBinMapper.selectById(param.getStationId());
        if(recycleBin == null){
            throw new Exception("站点不存在");
        }
        BeanUtil.copyProperties(param, recycleBin);
        recycleBinMapper.updateById(recycleBin);
    }

    @Override
    public Integer selectStationIdByAccountId(Integer accountId) throws Exception {
        Account account = accountMapper.selectById(accountId);
        if(account == null){
            throw new Exception("用户不存在");
        }
        RecycleBin recycleBin = recycleBinMapper.selectOne(new QueryWrapper<RecycleBin>().eq("chief_name", account.getAccountName()));
        if(recycleBin== null){
            throw new Exception("用户未绑定站点");
        }
        return recycleBin.getStationId();
    }

    @Override
    public PageInfo selectAllStation(SelectStationParam param) throws Exception {
        Page<RecycleBin> recycleBinPage = new Page<>(param.getPageNum(), param.getPageSize());
        QueryWrapper<RecycleBin> wrapper = new QueryWrapper<>();
        if(param.getStationName()!= null){
            wrapper.like("station_name", param.getStationName());
        }
        Page<RecycleBin> page = recycleBinMapper.selectPage(recycleBinPage, wrapper);
        PageInfo pageInfo = new PageInfo(page);
        return pageInfo;
    }


}
